<template>
  <div class="aompont">
    <van-pull-refresh
      v-model="refreshing"
      success-text="刷新成功"
      @refresh="onLoad"
    >
      <van-list
        @load="onLoad"
        :immediate-check="false"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        v-model="loading"
      >
        <atcsong
          v-for="itms in resultsList"
          :key="itms.art_id"
          :atcimg="itms"
        ></atcsong>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import atcsong from './atcsong.vue'
import { getArticlesApi } from '@/api'
export default {
  name: 'homeS',
  components: {
    atcsong
  },
  data() {
    return {
      resultsList: [],
      loading: false,
      timo: 0,
      finished: false,
      error: false,
      refreshing: false
    }
  },
  props: {
    atcList: [Number, String]
  },
  created() {
    this.getArticles()
  },
  methods: {
    async getArticles() {
      try {
        const {
          data: { data }
        } = await getArticlesApi(this.atcList, +new Date())
        this.resultsList = data.results

        this.timo = data.pre_timestamp
      } catch (error) {
        if (error.response?.status === 400) {
          this.$toast.fail(error.response.data.message)
        } else {
          throw error
        }
      }
    },
    async onLoad() {
      try {
        if (Math.random() < 0.2) {
          throw new Error()
        }
        const { data } = await getArticlesApi(this.atcList, this.timo)
        //将数据添加到数组中
        const res = data.data.results

        //如果为拉下刷新触发,则改变push方法
        if (this.loading) {
          this.resultsList.push(...res)
        } else {
          this.resultsList.unshift(...res)
        }
        //获取新的时间戳
        this.timo = data.data.pre_timestamp
        //设置为true,将不会进行网络请求,数据已经完成了
        if (data.data.pre_timestamp === null) {
          //没有数据则设置为true,不在加载
          this.finished = true
        }
      } catch (error) {
        this.error = true
      } finally {
        // 无论成功与否 每加载一次load,将loading改为fales将不会在发起请求
        this.loading = false
        //下拉刷新, 触发过后就改为false
        this.refreshing = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.aompont {
  height: calc(100vh - 100px - 92px - 83px);
  overflow: auto;
}
</style>
